package com.ejuornal.timer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.VelocityContext;
import org.springframework.scheduling.annotation.Scheduled;

import com.ejuornal.bean.Artical;
import com.ejuornal.bean.vo.Email;
import com.ejuornal.bean.vo.VO_SUbScribe_2;
import com.ejuornal.bean.vo.VO_SubScribe;
import com.ejuornal.service.ArticalService;
import com.ejuornal.service.PeriodicalService;
import com.ejuornal.service.SubscribeService;
import com.ejuornal.springutil.SpringUtil;
import com.ejuornal.util.StringUtil;
import com.ejuornal.util.ThreadPool;
import com.ejuornal.util.VelocityUtil;

public class PerperiodicalSubTimer {
    public List<VO_SUbScribe_2>  getData() {
        ArticalService articalService = (ArticalService) SpringUtil.getBean("articalService");
        PeriodicalService ps = (PeriodicalService) SpringUtil.getBean("periodicalService");
        SubscribeService s = (SubscribeService) SpringUtil.getBean("subscribeService");
		List<VO_SubScribe> v = ps.find();
		List<VO_SUbScribe_2> v2 = new ArrayList<VO_SUbScribe_2>();
		for(int i=0; i < v.size(); i++) {
			int periodicalId = v.get(i).getPeriodicalId();
			int perPeriodicalId = v.get(i).getPerPeriodicalId();
			System.out.println(periodicalId);
			List<String> emails = s.findByListPeriodicalId(periodicalId);
			List<Artical> articals = articalService.findByPerPeriodical(perPeriodicalId);
			VO_SUbScribe_2 vv = new VO_SUbScribe_2();
			vv.setEmail(emails);
			vv.setArtical(articals);
			vv.setV(v.get(i));
			v2.add(vv);
		}
		return v2;
	}
    @Scheduled(cron="40 * * * * ?")
    //@Scheduled(cron="0 30 1 * * ?")   //凌晨1：30执行期刊邮箱发送
	public void sendEmail() throws IOException {
		List<VO_SUbScribe_2> vv = getData();
		System.out.println("vv的长度：" + vv.size());
		//加入模板引擎
		String url="vm/perPeriodical_post.vm";
		ThreadPool tPool = new ThreadPool();
		Email email = new Email();
		email.setSubject("中国刊网邮件订阅");
		email.setMimetype("text/html");
		for(int i=0; i < vv.size(); i++) {
			List<String[]> emailAddrs = StringUtil.ListSubBlock(vv.get(i).getEmail());
			for(int j=0; j < emailAddrs.size(); j++) {
				email.setReceivers(emailAddrs.get(j));
				VelocityContext context = new VelocityContext();
				context.put("title",vv.get(i).getV());
				context.put("content", vv.get(i).getArtical());
				String emailContent = VelocityUtil.init(context, url);
				email.setMailContent(emailContent);
				tPool.sendEmail(email);
			}
		}
	}
	
	public static void main(String[] args) {
		try {
			new PerperiodicalSubTimer().sendEmail();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
